//
//  ViewController.m
//  Snake
//
//  Created by 李毅 on 16/9/18.
//  Copyright © 2016年 李毅. All rights reserved.
//

#import "ViewController.h"
#import "Node.h"
#import "snake.h"
#import "UIView+Explode.h"
#import <objc/runtime.h>
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //[self setWantsFullScreenLayout:YES];
    self.view.backgroundColor = [UIColor greenColor];
    self.view.layer.borderWidth = 0.5f;
    self.view.layer.borderColor = [[UIColor yellowColor] CGColor];
    // Do any additional setup after loading the view, typically from a nib.
    NSLog(@"%f,%f",self.view.frame.size.width,self.view.frame.size.height);
    //used, 320/480
    self.grid = [NSMutableArray array];
    
    
    
    float cell_h = [[UIScreen mainScreen] bounds].size.width/32;
    if (!_up) {
        _up = [UIButton buttonWithType:UIButtonTypeCustom];
        _up.frame = CGRectMake(0, 0, 60, 60);
        [_up setTitle:@"up" forState:UIControlStateNormal];
        _up.center =CGPointMake(self.view.frame.size.width/2, cell_h * 43);
        [_up addTarget:self action:@selector(moveUp) forControlEvents:UIControlEventTouchUpInside];
        _up.backgroundColor = [UIColor yellowColor];
        _up.layer.cornerRadius = 30;
        [_up setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [self.view addSubview:_up];
    }
    if (!_left) {
        _left = [UIButton buttonWithType:UIButtonTypeCustom];
        _left.frame = CGRectMake(0, 0, 60, 60);
        [_left setTitle:@"left" forState:UIControlStateNormal];
        _left.center =CGPointMake(self.view.frame.size.width/4, cell_h * 48);
        [_left addTarget:self action:@selector(moveLeft) forControlEvents:UIControlEventTouchUpInside];
        _left.backgroundColor = [UIColor yellowColor];
        _left.layer.cornerRadius = 30;
        [_left setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

        [self.view addSubview:_left];
    }
    if (!_right) {
        _right = [UIButton buttonWithType:UIButtonTypeCustom];
        _right.frame = CGRectMake(0, 0, 60, 60);
        [_right setTitle:@"right" forState:UIControlStateNormal];
        _right.center =CGPointMake(self.view.frame.size.width*3/4, cell_h * 48);
        [_right addTarget:self action:@selector(moveRight) forControlEvents:UIControlEventTouchUpInside];
        _right.backgroundColor = [UIColor yellowColor];
        _right.layer.cornerRadius = 30;
        [_right setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

        [self.view addSubview:_right];
    }
    if (!_down) {
        _down = [UIButton buttonWithType:UIButtonTypeCustom];
        _down.frame = CGRectMake(0, 0, 60, 60);
        [_down setTitle:@"down" forState:UIControlStateNormal];
        _down.center =CGPointMake(self.view.frame.size.width/2, cell_h * 53);
        [_down addTarget:self action:@selector(moveDown) forControlEvents:UIControlEventTouchUpInside];
        _down.backgroundColor = [UIColor yellowColor];
        _down.layer.cornerRadius = 30;
        [_down setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

        [self.view addSubview:_down];
    }
    
    
    if (!_score) {
        _score = [[UILabel alloc] init];
        _score.frame = CGRectMake(0, 0, 100, 30);
        _score.center = CGPointMake(50, cell_h * 41);
        _score.textAlignment = NSTextAlignmentCenter;
        [_score setTextColor:[UIColor whiteColor]];
        
        [self.view addSubview:_score];
    }
    
    if (!_reset){
        _reset = [UIButton buttonWithType:UIButtonTypeCustom];
        _reset.frame = CGRectMake(0, 0, 60, 60);
        _reset.center = CGPointMake(self.view.frame.size.width - 30, cell_h * 54);
        
        [_reset setTitle:@"restart" forState:UIControlStateNormal];
        _reset.backgroundColor = [UIColor redColor];
        [_reset setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];


        [_reset addTarget:self action:@selector(reStart) forControlEvents:UIControlEventTouchUpInside];
        _reset.layer.cornerRadius = 30;

        [self.view addSubview:_reset];

    }
    
    [self setup];
    self.snake = [[snake alloc] initWithXY:0 :0];
    
    
    //add gesture..
    UISwipeGestureRecognizer *swpL =[[ UISwipeGestureRecognizer alloc] init];
    [swpL setDirection:(  UISwipeGestureRecognizerDirectionLeft )];
    [swpL addTarget:self action:@selector(didSwipe:)];
    [self.view addGestureRecognizer:swpL];
    
    
    UISwipeGestureRecognizer *swpR =[[ UISwipeGestureRecognizer alloc] init];
    [swpR setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [swpR addTarget:self action:@selector(didSwipe:)];
    [self.view addGestureRecognizer:swpR];

    
    UISwipeGestureRecognizer *swpU =[[ UISwipeGestureRecognizer alloc] init];
    [swpU setDirection:(UISwipeGestureRecognizerDirectionUp)];
    [swpU addTarget:self action:@selector(didSwipe:)];
    [self.view addGestureRecognizer:swpU];
    
    
    UISwipeGestureRecognizer *swpD =[[ UISwipeGestureRecognizer alloc] init];
    [swpD setDirection:(UISwipeGestureRecognizerDirectionDown)];
    [swpD addTarget:self action:@selector(didSwipe:)];
    [self.view addGestureRecognizer:swpD];
    
    
    
    
    
    //
    //    [NSThread sleepForTimeInterval:10];
    //
    //    [_snake move];
    //    [self renderSnake:_snake];
    
    //
    //
    //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //            [self automate];
    //        });
    __weak ViewController *mm = self;
    __weak snake *ws = self.snake;
    //__weak Node *wf = self.food;
    
    _snake.moveFinishBlock = ^{
        
        //check boundry...
        Node *checkNode = [ws.body lastObject];

        if (checkNode.x < 0 || checkNode.x > 39 ) {
            NSLog(@"error..");

            [ws reset];
        

        }
        
        if (checkNode.y < 0 || checkNode.y > 31 ) {
            NSLog(@"error..");
            [ws reset];




        }
        //check suiside..
        for (Node *node in ws.body) {
            if (node == checkNode) {
                continue;
            }
            
            if (node.x == checkNode.x && node.y == checkNode.y) {
                //hit..
                NSLog(@"error..");
                

                [ws reset];

                [mm addFood];
                [mm renderSnake:ws];
                

                return ;
            }
        }
        
        
    
        
        //add new icon... check if eat food, then regenerate..
        Node *n1 = [ws.body lastObject];
        Node *n2 = mm.food;
        if ((n1.x == n2.x)&&(n1.y == n2.y)) {
            NSLog(@"got..");
            int index = n1.x + n1.y*40 ;
            UIView *uv = [mm.grid objectAtIndex:index];
            uv.tag = 0;
            
            [ws grow];

            
            [mm addFood];
            

            
        }
        int score = (int)([self.snake.body count ] -5);
        _score.text = [NSString stringWithFormat:@"当前分数:%d",score];
        [mm renderSnake:ws];

    };
    [_snake start];
    
    [self addFood];
    
    [self renderSnake:_snake];

    
}


- (void) didSwipe:(UISwipeGestureRecognizer *)recognizer{
    if([recognizer direction] == UISwipeGestureRecognizerDirectionLeft){
        //Swipe from right to left
        //Do your functions here
        [self moveLeft];
    }
    if([recognizer direction] == UISwipeGestureRecognizerDirectionRight){
        //Swipe from right to left
        //Do your functions here
        [self moveRight];
    }
    if([recognizer direction] == UISwipeGestureRecognizerDirectionUp){
        //Swipe from right to left
        //Do your functions here
        [self moveUp];
    }
    if([recognizer direction] == UISwipeGestureRecognizerDirectionDown){
        //Swipe from right to left
        //Do your functions here
        [self moveDown];
    }
    
}

- (UIImage *) screenshot {
    
    CGSize size = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
    
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    
    CGRect rec = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [self.view drawViewHierarchyInRect:rec afterScreenUpdates:YES];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(void) endAni{
    
    for (UIView *uv in self.grid) {
        [UIView animateWithDuration:1.0f animations:^{
            //uv.backgroundColor = [UIColor whiteColor];
            uv.alpha = 0;
        } completion:^(BOOL finished) {
            if(finished){
               // uv.backgroundColor = [UIColor blackColor];
                uv.alpha =1 ;
            }
        }];
    }
}

-(void)reStart{
    [self.snake reset];
    [self addFood];
    
    [self.snake start];
    
    [self renderSnake:_snake];

    
    
    
}

-(void)addFood{
    
    
    for (UIView *uv  in self.grid) {
        if (uv.tag == 1) {
            uv.tag = 0 ;
            uv.backgroundColor = [UIColor blackColor];
            uv.layer.cornerRadius = 0;

        }
           }
    
    
    
    int x = (arc4random() % 40)  ;
    int y = (arc4random() % 32) ;
    BOOL flag = NO;
    
    while (flag == NO) {
        for (Node *node in _snake.body) {
            if (node.x == x && node.y == y) {
                flag = NO;
                break;
            }
        }
        flag = YES;
        if (flag == NO) {
            x = (arc4random() % 40) ;
            y = (arc4random() % 32) ;

            continue;
        }
        
    }
    //add to map..
    int index = x + y*40 ;
    UIView *g1 = [_grid objectAtIndex:index];
    g1.backgroundColor = [UIColor redColor];
    g1.tag = 1;
    
    _food = [[Node alloc] initWithXY:x :y ] ;
    
    
}

-(void)moveUp{
    
    if (_snake) {
        if (_snake.dirct == 1 || _snake.dirct == 3) {
            return;
        }
        _snake.pre_direct = _snake.dirct;
        _snake.dirct = 1;

    }
    
}

-(void) moveLeft{
    if (_snake) {
        if (_snake.dirct == 2 || _snake.dirct == 4) {
            return;
        }
        _snake.pre_direct = _snake.dirct;
        _snake.dirct = 2;
        
    }
    
}

-(void)moveDown{
    if (_snake) {
        if (_snake.dirct == 1 || _snake.dirct == 3) {
            return;
        }
        _snake.pre_direct = _snake.dirct;
        _snake.dirct = 3;
    }
    
}

-(void)moveRight{
    if(_snake){
        if (_snake.dirct == 2 || _snake.dirct == 4) {
            return;
        }
        _snake.pre_direct = _snake.dirct;
        _snake.dirct = 4;
    }
}



-(void)automate{
    [_snake move];
    [self renderSnake:_snake];
    // [self automate];
    
}

-(void) renderSnake:(snake *)snake{
    //reset all..
    for (UIView *uv  in self.grid) {
        if (uv.tag == 1) {
            continue;
        }
        uv.backgroundColor = [UIColor blackColor];
        uv.layer.cornerRadius = 0;
    }
    
    for (Node *node in snake.body) {
        int x1 = node.x;
        int y1 = node.y;
        int index = x1 + y1*40 ;
        UIView *g1  = [self.grid objectAtIndex:index];
        g1.backgroundColor = [ UIColor whiteColor];
        g1.layer.cornerRadius = 0;
    }
    
    Node *node = snake.header;
    int x1 = node.x;
    int y1 = node.y;
    int index = x1 + y1*40 ;
    UIView *g1  = [self.grid objectAtIndex:index];
    g1.backgroundColor = [ UIColor redColor];
    g1.layer.cornerRadius = 5;
    
    if (snake.live == NO) {
        NSLog(@"dead..");
        UIImage *img = [self screenshot];
        UIImageView *uv = [[UIImageView alloc] initWithImage:img];
        [self.view addSubview:uv];
        [uv lp_explode];
        
    }
    
}


-(void)setup{
    [self.grid removeAllObjects];
    float w1 = [[UIScreen mainScreen] bounds].size.width/32;
    for (int i = 0; i<32; i++) {
        for (int j = 0 ; j < 40; j++) {
            UIView *uv =  [[UIView alloc] init];
            uv.frame = CGRectMake(0+w1*i, 0+w1*j, w1, w1);
            uv.backgroundColor = [UIColor blackColor];
            uv.layer.borderWidth = 1;
            uv.layer.borderColor = [[UIColor darkGrayColor] CGColor];
            [self.grid addObject:uv];
            [self.view addSubview:uv];
        }
    }
    
}



-(void)displayNode:(NSArray *) nodes{
    for (Node *node in nodes) {
        
        
    }
    
}
-(BOOL)prefersStatusBarHidden{
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
